package com.ruoyi.web.controller.glue;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.XlslUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.GlueSplice;
import com.ruoyi.system.service.IGlueSpliceService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 粘接接头信息
 *
 * @author ruoyi
 * @date 2025-03-31
 */
@RestController
@RequestMapping("/system/splice")
public class GlueSpliceController extends BaseController {
    @Autowired
    private IGlueSpliceService glueSpliceService;

    /**
     * 查询粘接接头信息列表
     *
     * @return {@link GlueSplice}
     */
    //@PreAuthorize("@ss.hasPermi('system:splice:list')")
    @GetMapping("/list")
    public TableDataInfo list(GlueSplice glueSplice) {
        startPage();
        List<GlueSplice> list = glueSpliceService.selectGlueSpliceList(glueSplice);
        return getDataTable(list);
    }


    /**
     * 导入粘接接头信息列表
     */
    //@PreAuthorize("@ss.hasPermi('system:splice:import')")
    @Log(title = "粘接接头信息", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importGlueSplice(@RequestBody MultipartFile file) {
        if (ObjectUtils.isEmpty(file)){
            return AjaxResult.success("请上传文件");
        }
        Workbook workBook = XlslUtil.getWorkBook(file);
        if (ObjectUtils.isEmpty(workBook)){
            return AjaxResult.success("工作簿不能为空");
        }

        Sheet sheetAt = workBook.getSheetAt(0);
        if (ObjectUtils.isEmpty(sheetAt)){
            return AjaxResult.success("表单不能为空");
        }

        Map<String, List<PictureData>> sheetPictureMap = XlslUtil.getSheetPictures(sheetAt);
        Row row = sheetAt.getRow(0);
        if (ObjectUtils.isEmpty(row)) {
            return AjaxResult.success("表头不能为空");
        }
        Cell cell = row.createCell(13);
        cell.setCellType(CellType.STRING);
        cell.setCellValue("图片行列号");
        int lastRowNum = sheetAt.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            Row row1 = sheetAt.getRow(i);
            Cell cell1 = row1.createCell(13);
            cell1.setCellValue(i + ":" + 4);
        }
        ExcelUtil<GlueSplice> util = new ExcelUtil<GlueSplice>(GlueSplice.class);
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            // 将 Workbook 写入到 ByteArrayOutputStream 中
            workBook.write(outputStream);
            // 将字节数组转换为 InputStream
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            Date nowDate = DateUtils.getNowDate();
            List<GlueSplice> glueSplices = util.importExcel(byteArrayInputStream);
            if (!CollectionUtils.isEmpty(glueSplices)){
                glueSplices=glueSplices.stream().filter(item->!ObjectUtils.isEmpty(item)).collect(Collectors.toList());
            }

            glueSplices.forEach(item -> {
                item.setCreateBy(getUserId().toString());
                item.setCreateTime(nowDate);
                if (sheetPictureMap.containsKey(item.getRowCellNum())) {
                    List<PictureData> pictureData = sheetPictureMap.get(item.getRowCellNum());
                    for (PictureData pictureDatum : pictureData) {
                        String absPath = null;
                        try {
                            // 获取图片的二进制数据
                            byte[] pictureBytes = pictureDatum.getData();
                            // 获取图片的建议扩展名
                            String extension = pictureDatum.suggestFileExtension();
                            if (extension == null || extension.isEmpty()) {
                                extension = "bin"; // 如果无法获取扩展名，默认使用 .bin
                            }
                            String fileName =DateUtils.datePath() + "/"+UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;

                            absPath = FileUploadUtils.getAbsoluteFile(RuoYiConfig.getUploadPath(), fileName).getAbsolutePath();
                            FileOutputStream fos = new FileOutputStream(absPath);
                            fos.write(pictureBytes);

                            String url =FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath(), fileName);
                            item.setGluePositionImage(StringUtils.isEmpty(item.getGluePositionImage())?url:item.getGluePositionImage()+","+url);
                            fos.flush();
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            if (CollectionUtils.isEmpty(glueSplices)){
                throw new RuntimeException("没有读取到表格数据，请检查表格表头是否与提供的模板表头一致。");
            }
            glueSpliceService.saveBatch(glueSplices);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.success(e.getMessage());
        }
        return AjaxResult.success();
    }


    /**
     * 导出粘接接头信息列表
     */
    //@PreAuthorize("@ss.hasPermi('system:splice:export')")
    @Log(title = "粘接接头信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GlueSplice glueSplice) {
        List<GlueSplice> list = glueSpliceService.selectGlueSpliceList(glueSplice);
        ExcelUtil<GlueSplice> util = new ExcelUtil<GlueSplice>(GlueSplice.class);

        util.exportExcel(response, list, "粘接接头信息数据");
    }

    /**
     * 下载粘接接头导入模板
     */
    //@PreAuthorize("@ss.hasPermi('system:splice:import')")
    @Log(title = "粘接接头信息", businessType = BusinessType.IMPORT)
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        ExcelUtil<GlueSplice> util = new ExcelUtil<GlueSplice>(GlueSplice.class);

        util.exportExcel(response, null, "基材导入模板");
    }


    /**
     * 获取粘接接头信息详细信息
     *
     * @return {@link GlueSplice}
     */
    //@PreAuthorize("@ss.hasPermi('system:splice:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(glueSpliceService.selectGlueSpliceById(id));
    }

    /**
     * 新增粘接接头信息
     */
    //@PreAuthorize("@ss.hasPermi('system:splice:add')")
    @Log(title = "粘接接头信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GlueSplice glueSplice) {
        return toAjax(glueSpliceService.insertGlueSplice(glueSplice));
    }

    /**
     * 修改粘接接头信息
     */
    //@PreAuthorize("@ss.hasPermi('system:splice:edit')")
    @Log(title = "粘接接头信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GlueSplice glueSplice) {
        return toAjax(glueSpliceService.updateGlueSplice(glueSplice));
    }

    /**
     * 删除粘接接头信息
     */
    //@PreAuthorize("@ss.hasPermi('system:splice:remove')")
    @Log(title = "粘接接头信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(glueSpliceService.deleteGlueSpliceByIds(ids));
    }

    /**
     * 粘接接头涉及产品三级目录
     *
     * @param dto
     * @return
     */
    @GetMapping("/getModel")
    public AjaxResult getModel(String dto) {
        List<String> list = glueSpliceService.getModel(dto);
        return AjaxResult.success(list);
    }


}
